package com.qiqu.controller;

import com.qiqu.commen.Const;
import com.qiqu.entity.Article;
import com.qiqu.entity.Enclosure;
import com.qiqu.entity.SearchRecords;
import com.qiqu.service.ArticleService;
import com.qiqu.service.EnclosureService;
import com.qiqu.service.SearchRecordsService;
import com.qiqu.utils.FetchVideoCover;
import com.qiqu.utils.JSONResult;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;


import static com.qiqu.commen.Const.PAGE_SIZE;


@RestController
@RequestMapping("article")
@Api(value = "文章相关接口",tags = {"文章相关接口controller"})
public class ArticleController {

    @Resource
    private ArticleService articleService;
    @Resource
    private EnclosureService enclosureService;
    @Resource
    private SearchRecordsService searchRecordsService;

    //添加文章--图片文章
    //添加文章--视频文章
    @ApiOperation(value = "添加文章----fk",notes = "添加文章")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "articleTitle", value = "文章标题", required = true,dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "articleDesc", value = "文章内容", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "type", value = "文章类型", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "tag", value = "分类", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "place", value = "地点", required = true, dataType = "string", paramType = "form")
    })
    @PostMapping(value={"/addArticle"},headers = "content-type=multipart/form-data")
    public String addArticle(String userId, String articleTitle,
                                 String articleDesc, int type,String tag,
                                 String place,
                                  @ApiParam(value = "视频",required = true)
                                          MultipartFile file) throws IOException {
        //文件保存路径
        String fileSpace=Const.FILE_SPACE;
        //数据库保存路径
        String uploadPathDB = "/rbook"+"/"+userId+"/video";

        FileOutputStream fileOutputStream =null;
        InputStream inputStream=null;
        String finalVideoPath="";
        String fileName="";
        try{
            if(file !=null){
                //获取文件名
                fileName=file.getOriginalFilename();


                if(StringUtils.isNotBlank(fileName)){
                    //文件上传的最终路径
                    finalVideoPath = fileSpace + uploadPathDB +"/"+fileName;
                    //设置数据库保存路径
                    uploadPathDB +="/"+fileName;

                    File outFile = new File(finalVideoPath);
                    if(outFile.getParentFile()!=null || outFile.getParentFile().isDirectory()){
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream,fileOutputStream);
                }
            }else {
                return "上传出错...";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "上传出错...";
        }finally {
            if(fileOutputStream !=null){
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        //保存文章信息数据库
        Article article = new Article();
        article.setTag(tag);
        article.setUserId(userId);
        article.setArticleTitle(articleTitle);
        article.setArticleDesc(articleDesc);
        article.setCoverPath(uploadPathDB);
        article.setStatus(Const.Status.on.code);//表发布中
        article.setCreateTime(new Date());
        article.setLikeCounts(0);
        article.setType(type);
        article.setPlace(place);
        Article article1= articleService.insert(article);
        if(type==1){
            String fileNamePrefix=uploadPathDB.split("\\.")[0];
            String coverPathDB=fileNamePrefix+".jpg";
            //对视频进行截图
            FetchVideoCover videoCover = new FetchVideoCover(Const.FFMPEG_EXE);
            videoCover.getCover(Const.FILE_SPACE+uploadPathDB,Const.FILE_SPACE+coverPathDB);

            Enclosure enclosure=new Enclosure();
            enclosure.setArticle(article1.getId());
            enclosure.setUserId(userId);
            enclosure.setPath(coverPathDB);
            enclosure.setType(Const.Role.photo.code);
            enclosure.setCreateTime(new Date());
            enclosure.setType(2);
            enclosureService.addEnclosure(enclosure);
        }
        return article1.getId();
    }

    //删除文章
    @ApiOperation(value = "删除文章--fk",notes = "删除文章")
    @ApiImplicitParam(name="articleId",value = "文章Id",required = true,dataType = "string",paramType = "query")
    @GetMapping("/delete")
    public JSONResult delete(String articleId) {
        articleService.deleteById(articleId);
        //删除附件内容
        enclosureService.deleteByArticle(articleId);
        return JSONResult.ok();
    }


    //获取个人文章列表
    @ApiOperation(value = "获取个人文章列表--fk",notes = "获取个人文章列表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name="page",value = "页码",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name="userId",value = "用户id",required = true,dataType = "string",paramType = "query")
    })
    @GetMapping("/personArticle")
    public JSONResult personArticle(String userId,Integer page) {

        if(page == null){
            page=1;
        }
        return JSONResult.ok(articleService.getPersonArticle(userId,page,PAGE_SIZE));

    }

    //分页查询文章
    //关键字搜索查询文章
    @ApiOperation(value = "获取文章列表--fk",notes = "获取文章列表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name="keyword",value = "关键字",required = false,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name="page",value = "页码",required = true,dataType = "int",paramType = "query")
    })
    @GetMapping("/queryArticle")
    public JSONResult queryArticle(Integer page,String keyword) {
        if(page == null){
            page=1;
        }
        return JSONResult.ok(articleService.getArticle(page,PAGE_SIZE,keyword));

    }

    //分页查询文章
    //关键字搜索查询文章（附近）
    @ApiOperation(value = "获取附近文章列表--fk",notes = "获取附近文章列表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name="keyword",value = "关键字",required = false,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name="page",value = "页码",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name="tag",value = "分类",required = false,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name="place",value = "地点",required = true,dataType = "string",paramType = "query"),
    })
    @GetMapping("/queryArticleNear")
    public JSONResult queryArticleNear(Integer page,String keyword,String place) {
        if(page == null){
            page=1;
        }
        return JSONResult.ok(articleService.getArticleNear(page,PAGE_SIZE,keyword,place));
    }

    //查询文章超级接口
    @ApiOperation(value = "获取文章超级接口--fk",notes = "获取文章超级接口")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name="keyword",value = "关键字",required = false,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name="page",value = "页码",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name="tag",value = "分类",required = false,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name="place",value = "地点",required = false,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name="userId",value = "用户Id",required = false,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name="isSave",value = "是否保存",required = false,dataType = "int",paramType = "query")
    })
    @GetMapping("/queryArticleAll")
    public JSONResult queryArticleAll(HttpServletRequest request, Integer page, String keyword, String place, String tag, String userId,Integer isSave) {
        if(page == null){
            page=1;
        }

        if(isSave==1){
            SearchRecords searchRecords = new SearchRecords();
            searchRecords.setContent(keyword);
            searchRecords.setUserId(userId);
            searchRecordsService.addSearchRecords(searchRecords);
        }
        return JSONResult.ok(articleService.getArticleAll(page,PAGE_SIZE,keyword,place,tag,userId));

    }

    //获取关注用户文章
    @ApiOperation(value = "获取关注用户文章--fk", notes = "获取关注用户文章")
    @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int", paramType = "query")
    @GetMapping("/LikeUPArticle")
    public JSONResult LikeUPArticle(HttpServletRequest request, Integer page){
        if(page == null){
            page=1;
        }
        String userId=request.getHeader("userId");
        return  JSONResult.ok(articleService.userLikeUPArticle(userId,page, Const.PAGE_SIZE));
    }

    //获取用户点赞的文章列表
    @ApiOperation(value = "获取用户点赞文章列表--fk", notes = "获取用户点赞文章列表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name="page",value = "页码",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name="userId",value = "用户id",required = true,dataType = "string",paramType = "query")
    })
    @GetMapping("/LikeArticle")
    public JSONResult LikeArticle(String userId, Integer page){
        if(page == null){
            page=1;
        }
        return JSONResult.ok(articleService.userLikeArticle(userId,page, Const.PAGE_SIZE));
    }

    //获取用户收藏的文章列表
    @ApiOperation(value = "获取用户收藏文章列表--fk", notes = "取消收藏文章")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name="page",value = "页码",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name="userId",value = "用户id",required = true,dataType = "string",paramType = "query")
    })
    @GetMapping("/collectionArticle")
    public JSONResult collectionArticle(String userId, Integer page){
        if(page == null){
            page=1;
        }
        return  JSONResult.ok(articleService.userCollection(userId,page, Const.PAGE_SIZE));
    }

    //发现文章列表
    @ApiOperation(value = "发现文章列表--fk", notes = "发现文章列表")
    @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int", paramType = "query")
    @GetMapping("/ArticleLikeCounts")
    public JSONResult ArticleLikeCounts( Integer page){
        if(page == null){
            page=1;
        }
        return  JSONResult.ok(articleService.getArticleLikeCounts(page, Const.PAGE_SIZE));
    }
}
